// stores/auth.ts
import { defineStore } from "pinia";

export interface User {
  id: number;
  username: string;
  email: string;
  createdAt: string; // 新增：注册时间
  lastLoginAt?: string; // 新增：最后登录时间（可选）
}

export const useAuthStore = defineStore("auth", {
  state: () => ({
    user: null as User | null,
    token: null as string | null,
  }),

  getters: {
    isAuthenticated: (state) => !!state.token,
    currentUser: (state) => state.user,

    // 新增：格式化注册时间
    formattedCreatedAt: (state) => {
      if (!state.user?.createdAt) return "未知";
      return new Date(state.user.createdAt).toLocaleDateString("zh-CN");
    },

    // 新增：格式化最后登录时间
    formattedLastLoginAt: (state) => {
      if (!state.user?.lastLoginAt) return "从未登录";
      return new Date(state.user.lastLoginAt).toLocaleString("zh-CN");
    },
  },

  actions: {
    setUser(user: User) {
      this.user = user;
    },

    setToken(token: string) {
      this.token = token;
    },

    clearAuth() {
      this.user = null;
      this.token = null;
    },

    // 新增：更新用户信息（部分更新）
    updateUser(partialUser: Partial<User>) {
      if (this.user) {
        this.user = { ...this.user, ...partialUser };
      }
    },

    // 新增：更新最后登录时间
    updateLastLoginTime() {
      if (this.user) {
        this.user.lastLoginAt = new Date().toISOString();
      }
    },
    // 从 localStorage 初始化状态
    initializeFromStorage() {
      if (process.client) {
        const storedUser = localStorage.getItem("auth-user");
        const storedToken = localStorage.getItem("auth-token");

        if (storedUser) {
          try {
            this.user = JSON.parse(storedUser);
          } catch (error) {
            console.error("解析存储的用户信息失败:", error);
            localStorage.removeItem("auth-user");
          }
        }

        if (storedToken) {
          this.token = storedToken;
        }
      }
    },
  },
});
